import json
import random
import re

from PIL import Image
from io import BytesIO
import jieba
import jieba.analyse
from https.HttpRequest import get_web, post_web

baseApi = "http://localhost"
captchaCodeApi = baseApi + "/adminapi/captcha_pro"  # crmeb登录时的验证码接口
loginApi = baseApi + "/adminapi/login"  # crmeb后台登录接口
addGoodsApi = baseApi + "/adminapi/product/product/"  # 新增商品接口
tokenValue = ""  # 登录token

dbPriceBidPercent = 1.3  # 标价百分比
dbPriceMarketPercent = 1.5  # 市场价百分比
imageUrlReg = r"data-lazyload-src=['\"]([^'\"]+)[^>]*>"  # 图片地址


def getInsertSql(bean, active):
    """
    获取插入商品的SQL
    'sales': str(getSaleCount()),
              'stock': '999',
              'add_time': str(current_time()), 'spec_type': '1', 'activity': '0,1,2,3'
    """

    picArr = []
    attrsArr = []
    detailNameArr = []
    index = 0

    sqlMap = {"disk_info": "", "sales": getSaleCount(), "logistics": ["1"], "freight": "4", "postage": 0,
              "recommend": [], "presale_day": 1,
              "presale": False, "video_open": False, "vip_product": False, "custom_form": [], "unit_name": "件",
              "is_show": 1, "is_benefit": 0, "is_postage": 0, "is_sub": [], "label_id": [], "selectRule": "",
              "coupon_ids": [], "command_word": "", "type": 0, "is_copy": 1, "couponName": [], "spec_type": 1,
              "is_virtual": 0, "video_link": "", "temp_id": 1, "virtual_type": 0, "recommend_list": [],
              "give_integral": 0, "recommend_image": "", "ficti": 0, "sort": 0, "id": 0,
              "activity": ["默认", "秒杀", "砍价", "拼团"]}

    if active % 10 == 0:
        sqlMap["is_hot"] = '1'
        sqlMap["is_best"] = '1'
        sqlMap["is_new"] = '1'
        sqlMap["is_good"] = '1'

    for item in bean:
        value = item.value
        if index == 0:
            sqlMap["store_name"] = value
            sqlMap["store_info"] = value
            sqlMap["keyword"] = ','.join(jieba.analyse.extract_tags(value, round(3, 5), allowPOS=['n']))
        elif index == 2:
            sqlMap["cate_id"] = [(int(value))]
        elif index == 4 or index == 5 or index == 6 or index == 7 or index == 8:  # 展示图
            if value is not None and value != '':
                picArr.append(value)
                if index == 4:
                    sqlMap["image"] = value
            if index == 8:
                sqlMap["slider_image"] = picArr
        elif index == 9 or index == 11 or index == 13 or index == 15 or index == 17:  # 规格名称
            if value is not None and value != '':
                detailNameArr.append(value)
                attrsArr.append(
                    {"value1": value, "detail": {"规格": value}, "pic": sqlMap["image"], "vip_price": 0, "stock": 999,
                     "bar_code": "", "weight": 0, "volume": 0, "brokerage": 0, "brokerage_two": 0})
            if index == 17:
                sqlMap["items"] = [{"value": "规格", "detail": detailNameArr}]
        elif index == 10 or index == 12 or index == 14 or index == 16 or index == 18:  # 规格价格
            if value is not None and value != '':
                if index == 10 and attrsArr[0] is not None:
                    attrsArr[0]["price"] = int(value)
                    attrsArr[0]["cost"] = int(value)
                    attrsArr[0]["ot_price"] = int(value / dbPriceBidPercent * dbPriceMarketPercent)

                if index == 12 and attrsArr[1] is not None:
                    attrsArr[1]["price"] = int(value)
                    attrsArr[1]["cost"] = int(value)
                    attrsArr[1]["ot_price"] = int(value / dbPriceBidPercent * dbPriceMarketPercent)

                if index == 14 and attrsArr[2] is not None:
                    attrsArr[2]["price"] = int(value)
                    attrsArr[2]["cost"] = int(value)
                    attrsArr[2]["ot_price"] = int(value / dbPriceBidPercent * dbPriceMarketPercent)

                if index == 16 and attrsArr[3] is not None:
                    attrsArr[3]["price"] = int(value)
                    attrsArr[3]["cost"] = int(value)
                    attrsArr[3]["ot_price"] = int(value / dbPriceBidPercent * dbPriceMarketPercent)

                if index == 18 and attrsArr[4] is not None:
                    attrsArr[4]["price"] = int(value)
                    attrsArr[4]["cost"] = int(value)
                    attrsArr[4]["ot_price"] = int(value / dbPriceBidPercent * dbPriceMarketPercent)
            if index == 18:
                sqlMap["attrs"] = attrsArr
        elif index == 19:
            imageArr = re.compile(imageUrlReg).findall(value)
            if imageArr is not None and len(imageArr) != 0:
                images = ""
                for item in imageArr:
                    images = images + r'<p><img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;" src="' + item + '"/></p>'
                sqlMap["description"] = images
            else:
                sqlMap["description"] = ""
        index = index + 1
    return sqlMap


def addGoodsInfo(p, active):
    """
    新增商品信息
    """
    result = post_web(addGoodsApi + "0", json.dumps(getInsertSql(p, active)), h={'Authori-zation': tokenValue})
    if result['status'] == 200:
        return True
    else:
        return False


def crmebLogin():
    """
    crmeb登录
    """
    if getCaptchaCode():
        captch = input("请输入图片验证码：")
        login = post_web(loginApi, {'account': 'admin', 'pwd': 'dxw19950620', 'imgcode': str(captch)})
        if login is not None:
            if login['status'] == 200:
                global tokenValue
                tokenValue = "Bearer " + login['data']['token']
                return "成功"
            else:
                return "登录失败"
        else:
            return "登录失败"
    else:
        return "获取图片验证码失败"


def getCaptchaCode():
    """
    获取登录验证码
    """
    imgCaptcha = get_web(captchaCodeApi)
    if imgCaptcha is not None:
        image = Image.open(BytesIO(imgCaptcha.content))
        if image.mode == 'P' or image.mode == 'RGBA':
            image = image.convert('RGB')
        image.save('../file/CaptchaCode.jpg')
        return True
    else:
        return False


def getSaleCount():
    """
    随机生成销量
    """
    return random.randint(100, 300)
